/**
 * 审查单 管理模块
 */

const router = require("koa-router")();
const Rb = require("./../models/rbSchema");
const Review = require("./../models/reviewSchema");
const ReviewRecard = require("./../models/reviewRecordsSchema");
const util = require("./../utils/util");

router.prefix("/review");

// 审查单列表
router.get("/list", async (ctx) => {
  // 解构前端传递的查询参数
  const { rbId, fraud, reviewFraud, upload_id, onlineReview, offlineReview } =
    ctx.request.query;
  // 解构分页参数
  const { page, skipIndex } = util.pager(ctx.request.query);
  // 定义查询条件
  let params = {};
  // 如果有传递参数，则添加到查询条件中
  if (rbId) params.rbId = rbId;
  if (reviewFraud && reviewFraud != "3") params.reviewFraud = reviewFraud;
  if (onlineReview && onlineReview != "2") params.onlineReview = onlineReview;
  if (offlineReview && offlineReview != "2")
    params.offlineReview = offlineReview;
  if (fraud && fraud != "2") params.fraud = fraud;
  if (upload_id) params.upload_id = upload_id;
  try {
    console.log("查询条件:", params); // 添加日志输出，查看查询条件
    // 根据条件查询所有审查单列表
    const query = Review.find(params, { _id: 0 });
    // 将查询到的结果进行分页处理
    const list = await query.skip(skipIndex).limit(page.pageSize);

    // 统计符合条件的总记录数
    const total = await Review.countDocuments(params);

    ctx.body = util.success({
      page: {
        ...page,
        total,
      },
      list,
    });
  } catch (error) {
    ctx.body = util.fail(`查询异常:${error.stack}`);
  }
});

// 报销单加入审查
router.post("/addReview", async (ctx) => {
  // 待审查的报销单id数组
  const { rbId } = ctx.request.body;
  // 修改当前审查状态
  try {
    // 获取审查报销单信息
    const updateData = {
      state: 1,
    };

    const res_updata = await Rb.findOneAndUpdate(
      { rbId },
      updateData,
      { new: true } // 返回更新后的文档
    );

    if (!res_updata) {
      ctx.body = util.fail("加入审查失败", util.CODE.BUSINESS_ERROR);
      return;
    }

    const { _id, rbId, upload_id, fraud, score, level } = await Rb.findOne(
      { rbId },
      "_id rbId upload_id fraud score level"
    );

    // 创建新的审查对象
    const review = new Review({
      _id: _id,
      rbId: rbId,
      upload_id: upload_id,
      fraud: fraud,
      score: score,
      level: level,
    });
    review.save();
  } catch (error) {
    ctx.body = util.fail(error.stack, "加入审查失败");
  }
});

// 报销单删除/批量删除
router.post("/delete", async (ctx) => {
  // 待删除的报销单id
  const { rbId } = ctx.request.body;
  // 将报销单状态改为未审查
  const updateData = {
    state: 0,
  };

  // 根据条件更改报销单信息
  const res_Rb = await Rb.findOneAndUpdate({ rbId }, updateData, { new: true }); // 返回更新后的文档);
  const res_Review = await Review.findOneAndDelete({ rbId });
  // 如果删除成功，则返回成功信息
  if (res_Review) {
    ctx.body = util.success("", "删除成功");
  } else {
    ctx.body = util.fail("删除失败");
  }
});

// 审查单编辑
router.post("/save", async (ctx) => {
  // 解构前端传递的参数，取出需要的参数
  const { rbId, onlineReview, offlineReview, reviewFraud, remark } =
    ctx.request.body;
  if (!rbId) {
    ctx.body = util.fail("参数错误", util.CODE.PARAM_ERROR);
    return;
  }
  try {
    // 更新审查单信息
    const updateData = {
      onlineReview,
      offlineReview,
      reviewFraud,
      remark,
    };

    const res = await Review.findOneAndUpdate(
      { rbId },
      updateData,
      { new: true } // 返回更新后的文档
    );

    if (!res) {
      ctx.body = util.fail("未找到该审查单", util.CODE.BUSINESS_ERROR);
      return;
    }

    ctx.body = util.success(res, "审查单更新成功");
  } catch (error) {
    ctx.body = util.fail(error.stack, "更新失败");
  }
});

// 审查结果提交
router.post("/submit", async (ctx) => {
  // 接收到的报销单id
  const {
    rbId,
    reviewFraud,
    onlineReview,
    offlineReview,
    remark,
    reviewUserId,
    reviewUserName,
  } = ctx.request.body;
  // 将报销单状态改为已审查
  const updateData = {
    state: 2,
    updateTime: new Date(),
  };

  // 根据条件更改报销单信息
  const res_Rb = await Rb.findOneAndUpdate({ rbId }, updateData, { new: true }); // 返回更新后的文档);
  const res_Review = await Review.findOneAndDelete({ rbId });
  // 新增一条审查记录
  try {
    const reviewRecord = new ReviewRecard({
      rbId: rbId,
      reviewFraud: reviewFraud,
      onlineReview: onlineReview,
      offlineReview: offlineReview,
      remark: remark,
      reviewUserId: reviewUserId,
      reviewUserName: reviewUserName,
    });
    reviewRecord.save();
    ctx.body = util.success("", "审查提交成功");
  } catch (error) {
    ctx.body = util.fail(error.stack, "审查提交失败");
  }
});

module.exports = router;
